//
//  TopNewsTableViewController.m
//  LPSNews
//
//  Created by lanou3g on 14-10-11.
//  Copyright (c) 2014年 LPS. All rights reserved.
//

#import "TopNewsViewController.h"
#import "TopNews.h"
#import "TopNewsTableViewCell.h"
#import "MJRefresh.h"
#import "AFHTTPRequestOperationManager.h"
#import "ScrollViewModel.h"
#import "TechDetailViewController.h"
#import "techMode.h"
#import "PhotoViewController.h"

#define ScrollViewIMG @"http://c.3g.163.com/nc/ad/headline/android/0-3.html"
#define Top_News @"http://c.3g.163.com/nc/article/headline/T1348647909107/"

static int number = 20;


@interface TopNewsViewController () <TechDetailViewControllerDelegate>
@property (nonatomic, retain) UIActivityIndicatorView *activityView;
@property (nonatomic, retain)NSMutableArray * scollImgArray;

@end

@implementation TopNewsViewController
- (void)dealloc
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    [_topNewsArray release];
    [super dealloc];
}
- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return self;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    UIActivityIndicatorView *activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    activityView.frame = CGRectMake(0, 0, 80, 80);
    activityView.center = CGPointMake(160, 170);
    activityView.backgroundColor = [UIColor lightGrayColor];
    activityView.alpha = 0.8;
    activityView.layer.cornerRadius = 5;
    activityView.layer.masksToBounds = YES;
    self.activityView = activityView;
    [activityView startAnimating];

    
    //获取轮播图的model
    [self getScrollViewData:ScrollViewIMG];
    //1.下拉刷新(进入刷新状态会调用self的headerRefreshing)
    [self.tableView addHeaderWithTarget:self action:@selector(headerRefreshing)];
    //2.上拉加载更多(进入刷新状态会调用self的footerRefreshing)
    [self.tableView addFooterWithTarget:self action:@selector(footerRefreshing)];

    [self.view addSubview:activityView];
    [self.view bringSubviewToFront:activityView];
    [activityView release];
    
}
#pragma mark 进入刷新状态
#pragma --------------------------------------------
- (void)headerRefreshing
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSString * headerUpdataString =[Top_News stringByAppendingFormat:@"%d-20.html",0];
        [self requestWebDataForURLString:headerUpdataString andIsDowndrag:YES];
    });
}
- (void)footerRefreshing
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        NSString * footerUpdateString = [Top_News stringByAppendingFormat:@"%d-20.html",number];
        [self requestWebDataForURLString:footerUpdateString andIsDowndrag:NO];
    });
}
#pragma mark - Table view data source
#pragma --------------------------------------------
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _topNewsArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TopNews * top = [_topNewsArray objectAtIndex:indexPath.row];
    //轮播图
    if (indexPath.row == 0) {
        return 210;
    }
    else{
        //图集
        if (top.imgextra != nil) {
            return 116;
        }
        //独家
        else if (top.editor != nil){
            return 165;
        }
    }
    return 85;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TopNews * topNews = [_topNewsArray objectAtIndex:indexPath.row];
    topNews.number =(int) indexPath.row;
    NSString * identifier = @"topNews";
    TopNewsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[[TopNewsTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier]autorelease];
    }
    [cell.scrollView removeFromSuperview];
    cell.pageControl.numberOfPages = 0;
    cell.titleLabel.text = nil;
    cell.digestLabel.text = nil;
    cell.newsImageView.image = nil;
    cell.secondImageView.image = nil;
    cell.thirdImageView.image = nil;
    cell.bottomLine.backgroundColor = [UIColor clearColor];
    
    cell.scrollImageArray = self.scollImgArray;
    cell.topNews = topNews;
    
    return cell;
}
//cell点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(_delegate && [_delegate respondsToSelector:@selector(topNewsViewControllerCancelSwipeGesture)])
    {
        [_delegate topNewsViewControllerCancelSwipeGesture];
    }
    
    
    
    TechMode *techData = _topNewsArray[indexPath.row];
    
    if (techData.photosetID == nil) {
        TechDetailViewController *techDetail = [[TechDetailViewController alloc] init];
        [self.navigationController pushViewController:techDetail animated:NO];
        techDetail.delegate = self;
        techDetail.docid = techData.docid;
        self.isOpen = techDetail.isOpen;
        [techDetail release];
    }
    else
    {
        PhotoViewController *photoDetail = [[PhotoViewController alloc] init];
        self.isOpen = NO;
        self.isOpen = photoDetail.isOpen;
        
        photoDetail.photosetID = techData.photosetID;
        [self.navigationController pushViewController:photoDetail animated:YES];
        
        [photoDetail release];
    }
}

- (void)techDetailViewControllerOpenSwipeGesture
{
    if(_delegate && [_delegate respondsToSelector:@selector(topNewsViewControllerOpenSwipeGesture)])
    {
        [_delegate topNewsViewControllerOpenSwipeGesture];
    }
}

#pragma 网络请求获取轮播图所需model
#pragma --------------------------------------------
- (void)getScrollViewData:(NSString *)urlString
{
    _scollImgArray = [[NSMutableArray alloc]init];
    NSURL * url = [NSURL URLWithString:urlString];
    NSURLRequest * request = [[NSURLRequest alloc]initWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        NSDictionary * scrdic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray * array = [scrdic objectForKey:[scrdic allKeys][0]];
        for (NSDictionary * temscrdic in array) {
            ScrollViewModel * model = [[ScrollViewModel alloc]init];
            [model setValuesForKeysWithDictionary:temscrdic];
            [_scollImgArray addObject:model];
            [model release];
        }
        [self.tableView reloadData];
    }];
}

#pragma 网络请求
#pragma --------------------------------------------
- (void)tableViewDownLoadDataForURLString:(NSString *)urlstring andIsDowndrag:(BOOL)isDowndrag
{
    if (_topNewsArray == nil) {
        _topNewsArray = [[NSMutableArray alloc]init];
        [self requestWebDataForURLString:urlstring andIsDowndrag:isDowndrag];
    }
}
- (void)requestWebDataForURLString:(NSString *)urlstring andIsDowndrag:(BOOL)isDowndrag
{
    NSMutableArray *requestDataArray = [[NSMutableArray alloc] init];
    AFHTTPRequestOperationManager *requestManager = [AFHTTPRequestOperationManager manager];
    [requestManager GET:urlstring  parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dict = responseObject;
        NSArray *keyarray = [dict allKeys];
        NSString *keyString = keyarray[0];
        NSArray *techArray = [dict objectForKey:keyString];
        for (NSDictionary *dict in techArray) {
            TopNews * games = [[TopNews alloc] init];
            [games setValuesForKeysWithDictionary:dict];
            [requestDataArray addObject:games];
            [games release];
        }
        if (isDowndrag) {
            self.topNewsArray = requestDataArray;
            [self.tableView headerEndRefreshing];
            number = 20;
        }else
        {
            [self.topNewsArray addObjectsFromArray:requestDataArray];
            number += 20;
            [self.tableView footerEndRefreshing];
        }
        [self.activityView stopAnimating];
        [self.activityView removeFromSuperview];

        [self.tableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        UILabel * textLable = [[UILabel alloc] init];
        textLable.frame = CGRectMake(0, 0, 140, 100);
        textLable.center = CGPointMake(160, 240);
        textLable.backgroundColor = [UIColor darkGrayColor];
        textLable.text = @"网络不给力";
        textLable.textColor = [UIColor whiteColor];
        textLable.textAlignment = NSTextAlignmentCenter;
        textLable.layer.cornerRadius = 8;
        textLable.layer.masksToBounds = YES;
        [self.view.window addSubview:textLable];
        textLable.alpha = 0;
        [UIView animateWithDuration:0.1 animations:^{
            [UIView animateWithDuration:0.1 delay:0.2 options:UIViewAnimationOptionCurveLinear animations:^{
                textLable.alpha = 0.8;
            } completion:^(BOOL finished) {
                [UIView animateWithDuration:0.5 delay:1 options:UIViewAnimationOptionCurveLinear animations:^{
                    textLable.alpha = 0;
                } completion:^(BOOL finished) {
                    [textLable removeFromSuperview];
                }];
            }];
        }];
        [textLable release];
        [self.tableView headerEndRefreshing];
        [self.tableView footerEndRefreshing];
        [self.activityView stopAnimating];
        [self.activityView removeFromSuperview];
    }];
    [requestDataArray release];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
 {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */

/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
 {
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source
 [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
 } else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
 }
 }
 */

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
 {
 }
 */

/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
 {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
 {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
